//
//  UICollectionViewCell+DWAutoHeight.m
//  BKJ
//
//  Created by 吴涛 on 16/3/2.
//  Copyright © 2016年 贝壳家iOS. All rights reserved.
//

#import "UICollectionViewCell+DWAutoHeight.h"









@implementation UICollectionViewCell (DWAutoHeight)

// associative 扩展属性用
const void *s_dw_itemBottomViewKey = "dw_itemBottomViewKey";
const void *s_dw_itemBottomOffsetToCellKey = "dw_itemBottomOffsetToCellKey";

+ (CGSize)dw_itemHeightForIndexPath:(NSIndexPath *)indexPath config:(DWItemConfigBlock)config{
  
  UICollectionViewCell *cell = [[self alloc]init];
  
  config(cell);
  
  return [cell private_dw_itemHeightForIndexPath:indexPath];
}

// associative 扩展属性用
- (void)setDw_itemBottomView:(UIView *)dw_itemBottomView{
  objc_setAssociatedObject(self,
                           s_dw_itemBottomViewKey,
                           dw_itemBottomView,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  
}

- (UIView *)dw_itemBottomView {
  return objc_getAssociatedObject(self, s_dw_itemBottomViewKey);
}


- (void)setDw_itemBottomOffsetToCell:(CGFloat)dw_itemBottomOffsetToCell {
  objc_setAssociatedObject(self,
                           s_dw_itemBottomOffsetToCellKey,
                           @(dw_itemBottomOffsetToCell),
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGFloat)dw_itemBottomOffsetToCell {
  NSNumber *valueObject = objc_getAssociatedObject(self, s_dw_itemBottomOffsetToCellKey);
  if ([valueObject respondsToSelector:@selector(floatValue)]) {
    return valueObject.floatValue;
  }
  
  return 0.0;
}




#pragma mark - Private Methods


- (CGSize)private_dw_itemHeightForIndexPath:(NSIndexPath *)indexPath {
  NSAssert(self.dw_itemBottomView != nil, @"您未指定cell排列中最后一个视图对象，无法计算cell的高度");
  
  // 调用方法，确定约束
  [self layoutIfNeeded];
  
  // 通过已确定的约束来得到最下面的控件的Frame； 然后通过Frame 来计算出cell的高度
  CGFloat cellHeight = self.dw_itemBottomView.frame.size.height + self.dw_itemBottomView.frame.origin.y;
  cellHeight += self.dw_itemBottomOffsetToCell;
  
  return CGSizeMake(SCREEN_WIDTH, cellHeight);
}





@end
